const { verify } = require('../util/jwt')
const util = require('util')

require('dotenv').config({ path: `./config/.env.${process.env.NODE_ENV}` })
const JWT_SECRET = process.env.JWT_SECRET
const User = require('../model/user')

module.exports = async (req, res, next) => {
  let token = req.headers['authorization']
  token = token ? token.split(`Bearer `)[1] : null
  if (!token) {
    return res.status(401).json({
      message: '用户未登录，请先登录'
    })
  }
  try {
    const decodedToken = await verify(token, JWT_SECRET)
    req.user = await User.findById(decodedToken.userId)
    next()
  } catch (err) {
    return res.status(401).json({
      message: '找不到用户',
      error: util.format(err)
    })
  }
}